package com.aiks.single.singlemavenproject.configuration;

import com.aiks.single.singlemavenproject.config.HikariDataSourceConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * dal数据访问自动装配类
 * {@link DataSourceTransactionManager}
 * {@link SqlSessionFactory}
 *
 * @author <a href="mailto:aiks_yuan@163.com">yuanzhen</a>
 * @date 2019-07-03 17:48
 * @see HikariDataSourceConfig
 * @since 1.0.0
 **/
@Order(0)
@Configuration
@EnableConfigurationProperties(HikariDataSourceConfig.class)
@EnableTransactionManagement
@MapperScan(basePackages = {"com.aiks.single.singlemavenproject.dao"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfiguration {

    @Bean("dataSource")
    public DataSource getHikariDataSource(HikariDataSourceConfig hikariDataSourceProperties) {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(hikariDataSourceProperties.getJdbcUrl());
        hikariDataSource.setUsername(hikariDataSourceProperties.getUsername());
        hikariDataSource.setPassword(hikariDataSourceProperties.getPassword());
        /**
         * 连接池中允许的最大连接数。缺省值：10；推荐的公式：((core_count * 2) + effective_spindle_count) -
         */
        hikariDataSource.setMaximumPoolSize(hikariDataSourceProperties.getMaximumPoolSize());
        /**
         *一个连接idle状态的最大时长（毫秒），超时则被释放（retired），缺省:10分钟 --
         */
        hikariDataSource.setIdleTimeout(hikariDataSourceProperties.getIdleTimeout());
        /**
         *  一个连接的生命时长（毫秒），超时而且没被使用则被释放（retired），
         *  缺省:30分钟，建议设置比数据库超时时长少30秒，
         *  参考MySQL wait_timeout参数（show variables like '%timeout%';）
         */
        hikariDataSource.setMaxLifetime(hikariDataSourceProperties.getMaxLifetime());
        hikariDataSource.setConnectionTimeout(hikariDataSourceProperties.getConnectionTimeout());
        hikariDataSource.setDriverClassName(hikariDataSourceProperties.getDriverClassName());
        hikariDataSource.setConnectionTestQuery(hikariDataSourceProperties.getConnectionTestQuery());
        return hikariDataSource;
    }

    @Primary
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        String path = "classpath*:mybatis/mysql/*.xml";
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(path));
        return factoryBean.getObject();
    }

}
